# -*- coding: utf-8 -*-
# @Author : breeze
# @Date   : 2021/5/20
# @File   : EG11_Ent1yearAdmVioCnt.py
# @E-mail : wangbaoshan@bbdservice.com

'''eof
name:申请企业近一年行政处罚总次数
code:EG11_Ent1yearAdmVioCnt
tableName:
columnName:
groups:企业通用模块
dependencies:EG_DSJ
type:常用指标
datasourceType:在线指标
description:
eof'''

import sys
import pandas as pd
import json
from datetime import datetime


def format_data(tableName):
    try:
        eg = EG_DSJ.get("data").get("R1103V3")[0].get(tableName)
        return eg if isinstance(eg, list) else [{}]
    except:
        return [{}]


# 统一转成datetime对象，只能转年月日的字符串
def date_format(time):
    import re
    r = re.compile(r'\D+')
    try:
        date = datetime.strptime(time, '%Y.%m.%d').strftime('%Y%m%d')
    except:
        try:
            date = datetime.strptime(time, '%Y-%m-%d').strftime('%Y%m%d')
        except:
            try:
                date = datetime.strptime(time, '%Y/%m/%d').strftime('%Y%m%d')
            except:
                try:
                    tmp = r.sub('', time)
                    date = datetime.strptime(tmp, '%Y%m%d').strftime('%Y%m%d')
                except:
                    date = None
    return date


def get_date_list():
    try:
        now = datetime.now()
        aaa = [(now + pd.tseries.offsets.DateOffset(months=i)).strftime('%Y%m%d') for i in [-12, 0]]
        return aaa
    except:
        return None


def get_result():
    null_type_list = ['', ' ', None, 'null', 'Null', 'NULL', '/', '-', '--']
    try:
        alter_list = format_data("caseInfoList")
        if alter_list == [{}]:
            return u'缺失值'
        else:
            if len(alter_list) >= 1:
                factor = []
                date_list = get_date_list()
                for i in alter_list:
                    alt_date = i.get("publicDate")
                    if alt_date not in null_type_list and date_format(alt_date[0:10]) not in null_type_list:
                        if date_list[0] < date_format(alt_date[0:10]) <= date_list[1]:
                            factor.append(1)
                        else:
                            factor.append(0)
                return sum(factor) if len(factor) > 0 else u'缺失值'
            else:
                return 0
    except:
        return u'缺失值'


if __name__ == "__main__":
    file_obj = open(r'../data/DAS/Past1YearBusinessChangeNum/EG_DSJ.json', encoding='utf-8', mode='r')
    content = file_obj.read()
    EG_DSJ = json.loads(content, strict=False)
    aa = get_result()
    print(aa)

result = get_result()
